<!-- HLS格式视频播放 -->
<template>
  <div class="hls_video">
    <video
      :id="'myHlsVideo' + videoIndex"
      class="video-js vjs-default-skin"
      controls
      style="width: 100%; height: 100%; object-fit: fill"
      :options="options"
    ></video>
  </div>
</template>

<script>
import Videojs from "video.js";
// import "videojs-contrib-hls";
import "video.js/dist/video-js.css";
import {
  defineComponent,
  nextTick,
  onUnmounted,
  onMounted,
  reactive,
  toRefs,
} from "vue";
export default defineComponent({
  props: {
    videoItem: {
      type: Object,
      default: () => {
        return {};
      },
    },
    videoIndex: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      options: {
        autoplay: true, // 设置自动播放
        muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音 （Chrome66及以上版本，禁止音视频的自动播放）
        preload: "auto", // 预加载
        loop: true, // 导致视频一结束就重新开始。
        controls: true, // 显示播放的控件
        language: "zh-CN", //汉化
        sources: [
          {
            type: "application/x-mpegURL",
            src: props.videoItem.video,
          },
        ],
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 无法播放媒体源时显示的默认信息。
        textTrackDisplay: false,
      },
      singlePlayer: null,
      videoUrl: props.videoItem.video,
    });

    onMounted(() => {
      nextTick(() => {
        initHls();
      });
    });

    const initHls = () => {
      try {
        state.singlePlayer = Videojs(
          "myHlsVideo" + props.videoIndex,
          state.options,
          function onPlayerReady() {}
        );
        state.singlePlayer.play();
      } catch (err) {
        console.log(err);
      }
    };

    onUnmounted(() => {
      if (state.singlePlayer) {
        state.singlePlayer.dispose();
      }
    });

    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
.hls_video {
  width: 100%;
  height: 100%;
  pointer-events: none;
}
</style>
